package com.sibu.yx.promotion.service.support.util;

import java.util.Date;
import java.util.Map;


import com.sibu.yx.promotion.common.vo.UserToken;
import com.sibu.yx.promotion.service.config.JwtTokenProperties;

import cn.hutool.core.bean.BeanUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class JwtTokenUtil {

    private static JwtTokenProperties jwtTokenProperties;

    private static final String TOKEN_CREAT_DT = "token_create_dt";

    public JwtTokenUtil(JwtTokenProperties jwtTokenProperties) {
        JwtTokenUtil.jwtTokenProperties = jwtTokenProperties;
    }

    /**
     * 根据负责生成JWT的token
     */
    public static String generateToken(UserToken userToken) {
        Map claims = BeanUtil.beanToMap(userToken);
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, jwtTokenProperties.getSecret())
                .claim(TOKEN_CREAT_DT, new Date())
                .compact();
    }


    public static UserToken getUserFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        if (claims == null) {
            return null;
        }
        UserToken userToken = UserToken.builder()
                .userId(claims.get("userId", String.class))
                .userName(claims.get("userName", String.class))
                .build();
        return userToken;

    }


    /**
     * 判断token是否已经失效
     */
    public static boolean isTokenExpired(String token) {
        Date expiredDate = getClaimsFromToken(token).getExpiration();
        return expiredDate.before(new Date());
    }


    /**
     * 生成token的过期时间
     */
    private static Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + jwtTokenProperties.getExpiration() * 1000);
    }


    /*
     * @description: 有效token
     * @param: [token]
     * @return: boolean
     * @author: yuwenbo@wljs.com
     * @date:2020-06-05
     * @time:14:32
     **/
    private static boolean isValidClaims(Claims claims) {
        Date expiredDate = claims.getExpiration();
        return expiredDate.after(new Date());
    }


    private static Claims getClaimsFromToken(String token) {

        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(jwtTokenProperties.getSecret())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("JWT格式验证失败:{}", token);

        }

        if (claims != null && isValidClaims(claims)) {
            return claims;

        }
        return null;
    }


}
